
package com.lzx.iteam.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Intents;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.widget.Toast;
import com.lzx.iteam.CloudDialerActivity;
import com.lzx.iteam.FakeDialog;
import com.lzx.iteam.R;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.MsgCenter;
import com.lzx.iteam.provider.CloudContactsDB;

public class CommonCodeUtil {
    private final static String TAG = "CommonCodeUtil";

    public static final char PAUSE = ',';

    public static final char WAIT = ';';

    public static final char WILD = 'N';
  
//    static DialerApp mDialerApp;
    
    private CommonCodeUtil() {
        // Can not create instance.
    }

    public static boolean phoneIsIdle(Activity activity) {

        if (activity == null) {
            return false;
        }
        TelephonyManager tm = (TelephonyManager) activity
                .getSystemService(Context.TELEPHONY_SERVICE);
        boolean result = (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE);

        return result;
    }
    public static boolean launchCallByNumber(Context activity, String number) {
//        mDialerApp = (DialerApp) activity.getApplicationContext();
        if (activity == null || TextUtils.isEmpty(number)) {
            return false;
        }
        
        try {
            PreferenceUtil mPreferenceUtil = PreferenceUtil.getInstance(activity);
            int isTwoSim = mPreferenceUtil.get(PreferenceUtil.IS_TWO_SIM, Integer.class);
           
            if(isTwoSim==1){
                String twoSimPackage = mPreferenceUtil.getString(PreferenceUtil.TWO_SIM_PACKAGE,null);
                boolean isHaveInstalled = false;
                MsgCenter mc = MsgCenter.getInstance(activity);
                PackageManager pm = activity.getPackageManager();
                try {
                    pm.getApplicationIcon(twoSimPackage);
                    isHaveInstalled = true;
                } catch (NameNotFoundException e) {
                    isHaveInstalled = false;
                }
                if(isHaveInstalled){
                    /*Bundle data = new Bundle();
                    data.putString("number", number);
                    Intent intent = new Intent(activity,TwoSimActivity.class);
                    intent.putExtras(data);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                    activity.startActivity(intent);*/
                    String type = mPreferenceUtil.getString(PreferenceUtil.TWO_SIM_TYPE,null);
                    Bundle data = new Bundle();
                    data.putString("number", number);
                    data.putString("type", type);
                    Intent intent = new Intent();
                    intent.setComponent(new ComponentName(twoSimPackage,twoSimPackage+".TwoSimActivity"));
                    intent.setAction(Constants.TWO_SIM_PLUGIN);
                    intent.putExtras(data);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                    activity.startActivity(intent);
                    long flag = mc.typeMsgExist(0, AsynHttpClient.SYNC_CHANNEL_HAVE_TWOSIM_PLUGIN);
                    if(flag!=-1){
                        MsgCenter.MsgDataItem item = mc.getMsgItem(flag);
                        item.isReaded = CloudContactsDB.MsgItem.READED;
                        item.msgTypeDrawableId = R.drawable.ic_msg_readed;
                        mc.updateMsgReaded(item);
                    }
                }else if(!isHaveInstalled){
                    String isFirst = mPreferenceUtil.getString("show_twosim_dialog", null);
                    if(isFirst == null){
                        showHelpDialog(activity, number);
                    }else{
                        Intent intent = getCallIntent(number);
                        activity.startActivity(intent);
                    }
                    long flag = mc.typeMsgExist(0, AsynHttpClient.SYNC_CHANNEL_HAVE_TWOSIM_PLUGIN);
                    if(flag==-1){
                        MsgCenter.MsgDataItem item = new MsgCenter.MsgDataItem();
                        item.cloudId = 0;
                        item.phoneNum = null;
                        item.isReaded = CloudContactsDB.MsgItem.UNREAD;
                        item.dateTime = System.currentTimeMillis();
                        item.execCode = AsynHttpClient.SYNC_CHANNEL_HAVE_TWOSIM_PLUGIN;
                        item.displayText = activity.getString(R.string.localmsg_twosims);
                        item.argList = "";
                        item.msgTypeDrawableId = R.drawable.ic_msg_type;
                        item.nextActionDrawableId = -1;
                        mc.addNewMsg(item);
                    }else{
                        MsgCenter.MsgDataItem item =  mc.getMsgItem(flag);
                        item.isReaded = CloudContactsDB.MsgItem.UNREAD;
                        item.msgTypeDrawableId = R.drawable.ic_msg_type;
                        mc.updateMsgReaded(item);
                    }
                }
            }else{
                Intent intent = getCallIntent(number);
                activity.startActivity(intent);
            }
            
            
        } catch (SecurityException e) {
            //: handle exception
        } catch (ActivityNotFoundException e) {
            Toast.makeText(activity, 
                    activity.getString(R.string.activity_not_found), 
                    Toast.LENGTH_LONG).show();
        }

        return true;
    }
    
    private static void showHelpDialog(Context context, String number){
        Intent intent = new Intent(context, FakeDialog.class);
        intent.putExtra(FakeDialog.DIALOG_TITLE, "提示");
        intent.putExtra(FakeDialog.DIALOG_MESSAGE, "监测到双卡插件，为了使您拨打更方便是否需要立刻下载?");
        intent.putExtra(FakeDialog.DIALOG_NUMBER, number);
        context.startActivity(intent);
    }
    

    public static boolean launchAddToContacts(Activity activity, String number) {
        if (activity == null || TextUtils.isEmpty(number)) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
        intent.putExtra(Intents.Insert.PHONE, number);
        intent.setType(Contacts.CONTENT_ITEM_TYPE);
        activity.startActivity(intent);

        return true;
    }

    public static boolean launchSendMessage(Context activity, String number, String body) {
        if (activity == null) {
            return false;
        }

        try {
            Intent intent;
            if (!StringUtil.isEmpty(number)) {
                Uri numberUri = Uri.fromParts(Constants.SCHEME_SMS, number, null);
                intent = new Intent(Intent.ACTION_SENDTO, numberUri);
            } else {
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setType("vnd.android-dir/mms-sms");
            }

            if (!StringUtil.isEmpty(body)) {
                intent.putExtra("sms_body", body);
            }
            activity.startActivity(intent);
//            ((Activity)activity).finish();
        } catch (ActivityNotFoundException e) {
            Toast.makeText(activity, activity.getString(R.string.activity_not_found),
                    Toast.LENGTH_LONG).show();
        }
        return true;
    }

    public static Intent getCallIntent(String number) {
        if (TextUtils.isEmpty(number)) {
            return null;
        }
        // Here, "number" can either be a PSTN phone number or a
        // SIP address. So turn it into either a tel: URI or a
        // sip: URI, as appropriate.
        String scheme = StringUtil.isUriNumber(number) ? Constants.SCHEME_SIP
                : Constants.SCHEME_TEL;
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts(scheme, number, null));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

        return intent;
    }

    public static Intent getCallVoipIntent(String number, String protocol) {
        /*
         * if(TextUtils.isEmpty(number) ||
         * CallLogContentHelper.PROTOCOL_SKYPE.equals(protocol)) {
         * //SpbLog.e(TAG, "Illegal arguments."); return null; }
         */
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(protocol + number));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

        return intent;
    }
    
    public static String getIpPrefix(Context context) {
//        mDialerApp = (DialerApp) context.getApplicationContext();
        String ipcodeS = PreferenceUtil.getInstance(context).get(PreferenceUtil.CONTACT_IPCALL, String.class);
        if (!StringUtil.isEmpty(ipcodeS)) {
            return ipcodeS;
        } else {
//            PhoneNumberArea phoneNumberArea = PhoneNumberArea.getInstance(context.getApplicationContext());
//            ipcodeS = phoneNumberArea.getIpcallNum(ipcodeS);
//            PreferenceUtil.getInstance(context).save(PreferenceUtil.CONTACT_IPCALL, ipcodeS);
            return "";
        }
    }

    public static String getRoamingCallBackCode(Context context, String number) {

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String mccmnc = tm.getSimOperator();
        
        String ret = null;
        
        if (!TextUtils.isEmpty(mccmnc)) {
            PhoneNumberArea.operator soperators = PhoneNumberArea.mccmncMap.get(mccmnc);
            switch (soperators) {
                case ChinaMobile:
                    ret = context.getString(R.string.roaming_call_back_cm_code, number);
                    break;
                case ChinaTelecom:
                    ret = context.getString(R.string.roaming_call_back_ct_code, number);
                    break;
                case ChinaUnicom:
                    ret = context.getString(R.string.roaming_call_back_cu_code, number);
                    break;
                default:
                    break;
            }
        }
        return ret;
    }
    
    /**
     * The value is linked to
     * {@link com.android.internal.telephony.CallerInfo#UNKNOWN_NUMBER}
     */
    public static final String UNKNOWN_NUMBER = "-1";

    /**
     * The value is linked to
     * {@link com.android.internal.telephony.CallerInfo#PRIVATE_NUMBER}
     */
    public static final String PRIVATE_NUMBER = "-2";

    /**
     * The value is linked to
     * {@link com.android.internal.telephony.CallerInfo#PAYPHONE_NUMBER}
     */
    public static final String PAYPHONE_NUMBER = "-3";

    public static boolean isNotCallBackNumber(String number) {
        // If number is unknown number, private number or payphone
        // number, can not call back.
        if (TextUtils.isEmpty(number) || number.equals(UNKNOWN_NUMBER)
                || number.equals(PRIVATE_NUMBER) || number.equals(PAYPHONE_NUMBER)) {
            return true;
        }
        return false;
    }
    
    public static boolean isDialable(String address) {
        for (int i = 0, count = address.length(); i < count; i++) {
            if (!isDialable(address.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public final static boolean isDialable(char c) {
        return (c >= '0' && c <= '9') || c == '*' || c == '#' || c == '+' || c == WILD || c == PAUSE || c == WAIT;
    }

    public static boolean networkUnavailable(Context c) {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;
        ConnectivityManager cm = (ConnectivityManager) c.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null) {
            if (ni.getType() == ConnectivityManager.TYPE_WIFI 
                    && ni.isConnectedOrConnecting()) {
                haveConnectedWifi = true;
            } else if (ni.getType() == ConnectivityManager.TYPE_MOBILE 
                    && ni.isConnectedOrConnecting()) {
                haveConnectedMobile = true;
            }
        }
        
        return !haveConnectedWifi && !haveConnectedMobile; 
    }

    public static void addShortcut(Activity a) {
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        shortcut.putExtra("duplicate", false);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, a.getString(R.string.app_name));
        
        Intent intent = new Intent(a, CloudDialerActivity.class);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setAction(Intent.ACTION_MAIN);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
    
        ShortcutIconResource iconRes = ShortcutIconResource.fromContext(
                a, R.drawable.cloud);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
    
        a.sendBroadcast(shortcut);
    }

    // 5-31 heihei: no need to prompt the user
//    public static void firstDialAlert(final Context context, final PreferenceUtil prefUtil) {
//        final Dialog dialog = new Dialog(context, 
//                android.R.style.Theme_Translucent_NoTitleBar);
//        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        dialog.setContentView(R.layout.first_dial_alert_when_click);
//        
//        Button singleClick = (Button) dialog.findViewById(R.id.first_dial_btn_single_click);
//        Button longClick = (Button) dialog.findViewById(R.id.first_dial_btn_long_click);
//        
//        singleClick.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                prefUtil.save(PreferenceUtil.FIRST_DIAL_ALERT_WHEN_CLICK, 
//                        Boolean.TRUE);
//                IphoneDialogUtil.showCustomMessageOK(context, 
//                        R.string.first_dial_attention_title,
//                        R.string.first_dial_attention_message, 
//                        R.string.i_known); 
//                dialog.dismiss();
//            }
//        });
//        longClick.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                prefUtil.save(PreferenceUtil.FIRST_DIAL_ALERT_WHEN_CLICK, 
//                        Boolean.TRUE);
//                prefUtil.save(PreferenceUtil.LONG_CLICK_DIAL, 
//                        Boolean.TRUE);
//                dialog.dismiss();
//            }
//        });
//        
//        dialog.show();
//    }
}
